package com.huiminpay.merchant.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.RandomUuidUtil;
import com.huiminpay.merchant.convert.AppConvert;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.merchant.entity.App;
import com.huiminpay.merchant.mapper.AppMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class AppServiceImpl implements IAppService {
    @Autowired
    AppMapper appMapper;

    @Override
    public AppDTO createApp(AppDTO appDTO) throws BusinessException{
        // 0.非空校验

        // 1.校验应用（校验就是名称）
        isExistAppName(appDTO);

        // 2 保存应用信息

        // 对象转换
        App app = AppConvert.INSTANCE.dto2entity(appDTO);
        // 业务隐藏参数设置
        app.setAppId(RandomUuidUtil.getUUID());
        appMapper.insert(app);

        return AppConvert.INSTANCE.entity2dto(app);
    }

    @Override
    public List<AppDTO> queryMerchantApp(Long merchantId) throws BusinessException {
        if(merchantId == null){
            throw new BusinessException(CommonErrorCode.E_100105);
        }
        // 根据商户id查询应用列表
        QueryWrapper<App> qw = new QueryWrapper<>();
        qw.lambda().eq(App::getMerchantId,merchantId);
        List<App> apps = appMapper.selectList(qw);

        return AppConvert.INSTANCE.listEntity2listDto(apps);
    }

    @Override
    public AppDTO myAppInfo(String appId) {
        if(StringUtils.isEmpty(appId)){
            throw new BusinessException(CommonErrorCode.E_100105);
        }
        QueryWrapper<App> qw = new QueryWrapper<>();
        qw.lambda().eq(App::getAppId,appId);
        App app = appMapper.selectOne(qw);

        return AppConvert.INSTANCE.entity2dto(app);
    }

    @Override
    public Boolean queryAppInMerchant(String appId, Long merchantId) {
        QueryWrapper<App> qw = new QueryWrapper<>();
        qw.lambda().eq(App::getAppId,appId).eq(App::getMerchantId,merchantId);
        Integer integer = appMapper.selectCount(qw);

        return integer>0;
    }

    /**
     * 判断应用名是否重复
     * @param appDTO
     */
    private void isExistAppName(AppDTO appDTO) {
        QueryWrapper<App> qw = new QueryWrapper<>();
        qw.lambda().eq(App::getAppName,appDTO.getAppName());
        Integer integer = appMapper.selectCount(qw);
        if(integer>0){
            throw new BusinessException(CommonErrorCode.E_200238);
        }
    }
}
